package sandeep.databases;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class WorkingwithdatabasesActivity extends Activity {
    /** Called when the activity is first created. */
	
	
	DatabaseHelper helper;
	EditText title;
	Cursor model;
	DatabaseAdapter adapter;
	Button save;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        helper = new DatabaseHelper(this);
        
        //Get XML parts
        title = (EditText)findViewById(R.id.title);
        save = (Button)findViewById(R.id.save);
        save.setOnClickListener(onSave);
        model=helper.getAll();
        startManagingCursor(model);
        adapter=new DatabaseAdapter(model);
        ListView list=(ListView)findViewById(R.id.list);
        list.setAdapter(adapter);
        
        //    helper.getTitle(model.getString(0));
    }
    
    
    //when the activity closes
    @Override
    public void onDestroy() {
    super.onDestroy();
    helper.close();
    }
    
    //to be executed when the save button is tapped
    private View.OnClickListener onSave = new View.OnClickListener() {
		
		public void onClick(View v) {
			
			//Makes sure that the title field is not blank
			if (title.getText().toString() != null && title.getText().toString() != "")
			{
				helper.insert(title.getText().toString());
				title.setText(null);
				
				model.requery();
				
				
				
				
				
			}
		}
	};
	
	
	
	class DatabaseAdapter extends CursorAdapter{
		
		

		public DatabaseAdapter(Cursor c) {
			super(WorkingwithdatabasesActivity.this, c);
			
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			DatabaseHolder holder = (DatabaseHolder) view.getTag();
			holder.populateFrom(cursor, helper);
			
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater=getLayoutInflater();
			View row=inflater.inflate(R.layout.row, parent, false);
			DatabaseHolder holder=new DatabaseHolder(row);
			row.setTag(holder);
			return row;
		}
		
		
		
		
	}
	static class DatabaseHolder {
	    private TextView title;
	    
	    DatabaseHolder(View row) {
	      title=(TextView)row.findViewById(R.id.Title);
	    }
	    
	    void populateFrom(Cursor c, DatabaseHelper helper) {
	      title.setText(helper.getTitle(c));
	  
	    }
	  }
	
}